<template>
  <div class="table-page">
    <a-form label-align="right" auto-label-width :model="listParams" size="small" class="form my-10">
      <a-row :gutter="16" wrap>
        <a-col :xs="12" :md="8" :lg="6" :xl="3" :xxl="3">
          <a-form-item field="keyword" hide-label>
            <a-input
              v-model="listParams.keyword"
              placeholder="输入关键字检索"
              @press-enter="changeCurrent(1)"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="8" :lg="6" :xl="3" :xxl="3">
          <a-form-item field="goodsId" hide-label>
            <a-input
              v-model="listParams.goodsId"
              placeholder="输入商品ID检索"
              @press-enter="changeCurrent(1)"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="4">
          <a-form-item field="categoryId" hide-label>
            <a-cascader
              :options="cateList"
              v-model="listParams.categoryId"
              placeholder="选择分类筛选"
              allow-clear
              @change="changeCurrent(1)"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="4">
          <a-form-item field="buyerCircleAuthorId" hide-label>
            <a-cascader
              :options="authorList"
              v-model="listParams.buyerCircleAuthorId"
              placeholder="请选择发布人"
              @change="changeCurrent(1)"
            />
          </a-form-item>
        </a-col>
        <a-col :xs="12" :md="8" :lg="6" :xl="4" :xxl="4">
          <a-form-item field="date" hide-label>
            <a-date-picker show-time v-model="listParams.date" @change="changeCurrent(1)" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-space>
            <a-button type="primary" size="small" @click="changeCurrent(1)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button size="small" @click="onResetSearch">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-form>
    <GiTable
      row-key="id"
      id="buyerCircleHotSelling"
      ref="tt"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :row-selection="{ type: 'checkbox', showCheckedAll: true }"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      @sorter-change="onSorterChange"
      @refresh="getTableData"
    >
      <template #custom-extra>
        <a-button type="primary" size="small" @click="onAddOrEdit(false)">
          <template #icon><icon-plus /></template>
          <span>新增</span>
        </a-button>
        <!-- <a-button v-if="selectedKeys.length > 0" type="primary" size="small" @click="onDeleteBatch(false)">
          <template #icon><icon-delete /></template>
          <span>批量删除</span>
        </a-button> -->
      </template>
      <template #publisherInfo="{ record }">
        <div class="flex flex-a-c">
          <a-image height="60" width="60" :src="record.authorAvatar"></a-image>
          <div class="ml-10 flex-col">
            <span class="font-bold text333 text-size-18 opacity-9">{{ record.author }}</span>
            <span>{{ record.publishedAt }}</span>
          </div>
        </div>
      </template>
      <template #goodsInfo="{ record }">
        <template v-if="record.goodsLists.length">
          <a-popover position="right" v-for="item in record.goodsLists.slice(0, 1)" :key="item.goodsId">
            <div class="text-overflow-2 cursor-pointer">
              <icon-tags />
              {{ item.title }}
            </div>
            <template #content>
              <div class="flex-col max-450">
                <a-image width="120" height="120" class="mr-10 cursor-pointer" :src="item.picUrl" />
                <div class="flex-col m-relative flex-1 overflow-hidden">
                  <div style="min-height: 22px" class="my-2 line-h-24 text-overflow-2">
                    <div class="m-absolute t-0 l-0" v-if="item.sourceTypeName">
                      <a-tag color="red">{{ item.sourceTypeName }}</a-tag>
                    </div>
                    <div
                      :style="{
                        textIndent: `${item.sourceTypeName ? item.sourceTypeName.length * 14 + 16 : 0}px`
                      }"
                    >
                      <ms-copy-div
                        :text="item.title"
                        :goods="{
                          goodsId: item.goodsId,
                          sourceType: item.sourceType,
                          activityId: item.activityId
                        }"
                      ></ms-copy-div>
                    </div>
                  </div>
                  <div class="flex flex-a-c text-size-13 text808080 my-2" v-if="item.shopName">
                    <img src="@/assets/images/dianpu.png" alt="" class="mr-2 w-4n h-4n" />
                    <span class="text-overflow-1 flex-1">{{ item.shopName }}</span>
                  </div>
                  <div class="flex flex-a-c my-2">
                    <span class="textd43030 text-size-14 font-bold"
                      ><span class="text-through text999 text-size-12" v-if="item.originalPrice"
                        >￥{{ item.originalPrice }}</span
                      ><span v-if="item.actualPrice">￥{{ item.actualPrice }}</span>
                    </span>
                  </div>
                  <div class="text-size-12 flex flex-a-c">
                    <ms-copy-div showLeftTitle :text="item.goodsId" title="商品ID"></ms-copy-div>
                  </div>
                  <div class="text-size-12 flex flex-a-c">
                    <ms-copy-div showLeftTitle :text="item.activityId" title="商品券ID"></ms-copy-div>
                  </div>
                </div>
              </div>
            </template>
          </a-popover>
          <template v-if="record.goodsLists.length > 1">
            <a-button type="text" size="small" @click="onMore(record.id, !record.isOpen)">
              {{ record.isOpen ? '收起' : '展开全部' }}（共{{ record.goodsLists.length }}条）
            </a-button>
          </template>
        </template>
        <span v-else>--</span>
      </template>
      <template #expand-row="{ record }">
        <a-card class="bgfff">
          <a-table
            size="mini"
            class="bgfff"
            :show-header="false"
            :columns="goodsColumns"
            :data="record.goodsLists"
            :pagination="false"
            :scroll="{ x: '100%', y: 500 }"
          >
            <template #info="{ record }">
              <div class="flex">
                <a-image width="80" height="80" class="mr-10 cursor-pointer" :src="record.picUrl" />
                <div class="flex-col m-relative flex-1 overflow-hidden">
                  <div style="min-height: 22px" class="my-2 line-h-24 text-overflow-2">
                    <div class="m-absolute t-0 l-0" v-if="record.sourceTypeName">
                      <a-tag color="red">{{ record.sourceTypeName }}</a-tag>
                    </div>
                    <div
                      :style="{
                        textIndent: `${record.sourceTypeName ? record.sourceTypeName.length * 14 + 16 : 0}px`
                      }"
                    >
                      <ms-copy-div
                        :text="record.title"
                        :goods="{
                          goodsId: record.goodsId,
                          sourceType: record.sourceType,
                          activityId: record.activityId
                        }"
                      ></ms-copy-div>
                    </div>
                  </div>
                  <div class="flex flex-a-c text-size-13 text808080 my-2" v-if="record.shopName">
                    <img src="@/assets/images/dianpu.png" alt="" class="mr-2 w-4n h-4n" />
                    <span class="text-overflow-1 flex-1">{{ record.shopName }}</span>
                  </div>
                </div>
              </div>
            </template>
          </a-table>
        </a-card>
      </template>
      <template #isShow="{ record }">
        <a-switch
          :checked-value="1"
          :unchecked-value="0"
          v-model="record.isShow"
          :before-change="handleChangeStatus.bind(null, record, 'isShow')"
        ></a-switch>
      </template>
      <template #isTop="{ record }">
        <a-switch
          :checked-value="1"
          :unchecked-value="0"
          v-model="record.isTop"
          :before-change="handleChangeStatus.bind(null, record, 'isTop')"
        ></a-switch>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="onAddOrEdit(record.id)"> 编辑 </a-button>
        <a-button type="text" size="small" @click="onDeleteBatch(record.id)"> 删除 </a-button>
      </template>
    </GiTable>
    <EditDrawer
      ref="EditDrawerRef"
      @getTableData="getTableData"
      :cateList="cateList"
      :platformList="platformList"
      :authorList="authorList"
    ></EditDrawer>
  </div>
</template>

<script setup>
import { Modal, Message } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'
import { usePlatform } from '@/hooks/app'
import MsCopyDiv from '@/components/MsCopyDiv/index.vue'
import {
  buyerCirclePreferredList,
  buyerCirclePreferredCate,
  buyerCirclePreferredToggle,
  buyerCirclePreferredDelete,
  buyerCircleAuthorSelect
} from '@/apis'
import EditDrawer from './EditDrawer.vue'

defineOptions({ name: 'buyerCircleHotSelling' })

const columns = ref([
  {
    title: '发布人信息',
    width: 200,
    slotName: 'publisherInfo'
  },
  {
    title: '商品信息',
    width: 200,
    slotName: 'goodsInfo'
  },
  {
    title: '分类',
    width: 100,
    render: (data) => {
      const text = data.record.categoryName
      return text || '--'
    }
  },
  {
    title: '文案内容',
    width: 200,
    render: (data) => {
      const text = data.record.content
      return h(MsCopyDiv, { text, line: 2 })
    }
  },
  {
    title: '分享数量',
    width: 100,
    dataIndex: 'shareNum'
  },
  {
    title: '是否启用',
    width: 100,
    slotName: 'isShow'
  },
  {
    title: '是否置顶',
    width: 100,
    slotName: 'isTop'
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])

const goodsColumns = ref([
  {
    title: '商品信息',
    width: 200,
    slotName: 'info'
  },
  {
    title: '商品ID',
    width: 180,
    render: (data) => {
      const text = data.record.goodsId
      return h(MsCopyDiv, { text, title: '商品ID', line: 2, showLeftTitle: true })
    }
  },
  {
    title: '商品券ID',
    width: 180,
    render: (data) => {
      const text = data.record.activityId
      return h(MsCopyDiv, { text, title: '商品券ID', line: 2, showLeftTitle: true })
    }
  },
  {
    title: '原价',
    width: 80,
    render: (data) => {
      const text = data.record.originalPrice
      return `原价：${text}元`
    }
  },
  {
    title: '现价',
    width: 80,
    render: (data) => {
      const text = data.record.actualPrice
      return `现价：${text}元`
    }
  }
])

const EditDrawerRef = ref()
const loading = ref(false)
const tableData = ref([])
const selectedKeys = ref([])
const cateList = ref([])
const authorList = ref([])
const tt = ref()

const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 10 })

const listParams = reactive({
  page: 1,
  pageSize: 10,
  orderBy: undefined,
  sort: undefined,
  keyword: undefined,
  categoryId: undefined,
  buyerCircleAuthorId: undefined,
  goodsId: undefined,
  date: undefined,
  pid: 10
})

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.pageSize = pagination.pageSize
    const res = await buyerCirclePreferredList(listParams)
    tableData.value = res.data.list.map((item) => {
      return { ...item, isOpen: false }
    })
    setTotal(res?.data?.meta?.pagination?.total || 0)
  } finally {
    loading.value = false
  }
}
getTableData()

// 获取分类信息
const getCateList = async () => {
  const res = await buyerCirclePreferredCate({ pid: 10 })
  cateList.value = res.data.list
}
getCateList()

// 获取发布者信息
const getAuthorList = async () => {
  const res = await buyerCircleAuthorSelect()
  authorList.value = res.data.list
}
getAuthorList()

// 获取平台信息
const { platformList, getPlatformList } = usePlatform()
getPlatformList()

// 添加/编辑
const onAddOrEdit = (id) => {
  EditDrawerRef.value?.addOrEdit(id)
}

// 点击展开更多
const onMore = (id, type) => {
  if (type) {
    tableData.value.forEach((item) => {
      item.isOpen = false
    })
    tt.value.tableRef.expandAll(false)
  }
  tt.value.tableRef.expand(id, type)
  const index = tableData.value.findIndex((item) => {
    return item.id === id
  })
  tableData.value[index].isOpen = type
}

// 改变列表中的切换按钮状态
const handleChangeStatus = async (record, str, newValue) => {
  await new Promise((resolve, reject) => {
    buyerCirclePreferredToggle({ id: record.id, [str]: newValue })
      .then(() => {
        Message.success('操作成功')
        getTableData()
        resolve(true)
      })
      .catch(() => {
        reject()
      })
  })
}

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

//升降序发生改变
const onSorterChange = (dataIndex, direction) => {
  listParams.orderBy = direction ? (direction === 'ascend' ? 'asc' : 'desc') : undefined
  listParams.sort = listParams.orderBy ? dataIndex : undefined
  changeCurrent(1)
}

// 重置筛选查询
const onResetSearch = () => {
  listParams.keyword =
    listParams.categoryId =
    listParams.buyerCircleAuthorId =
    listParams.goodsId =
    listParams.date =
      undefined
  changeCurrent(1)
}

// 删除数据
const onDeleteBatch = (id) => {
  Modal.warning({
    title: '提示',
    content: '是否确认删除？',
    hideCancel: false,
    onOk: () => {
      loading.value = true
      // const ids = id ? id.toString() : selectedKeys.value.join(',')
      buyerCirclePreferredDelete({ id })
        .then(() => {
          // selectedKeys.value = []
          Message.success('删除成功')
          getTableData()
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}
</script>

<style lang="scss" scoped>
.textd43030 {
  color: #d43030;
}

.max-450 {
  max-width: 450px;
}
</style>
